package cn.com.swu.mianyangapp.ui.todo;

import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.*;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import cn.com.swu.mianyangapp.R;
import cn.com.swu.mianyangapp.databinding.FragmentTodoBinding;
import cn.com.swu.mianyangapp.net.NetRepository;
import cn.com.swu.mianyangapp.net.TodoNetRepository;
import cn.com.swu.mianyangapp.result.UserInfo;
import cn.com.swu.mianyangapp.ui.todo.entity.NewTodo;
import cn.com.swu.mianyangapp.ui.todo.entity.Proc;
import cn.com.swu.mianyangapp.ui.todo.entity.Step;
import cn.com.swu.mianyangapp.ui.todo.entity.Todo;
import cn.com.swu.mianyangapp.ui.todo.result.AddTodoResult;
import cn.com.swu.mianyangapp.ui.todo.result.TodoListResult;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.gson.Gson;
import okhttp3.ResponseBody;
import org.jetbrains.annotations.NotNull;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class TodoFragment extends Fragment {

    private TodoViewModel mViewModel;
    private FragmentTodoBinding binding;
    private ConstraintLayout conTodoMain;
    private ConstraintLayout conTodoProc;
    private ConstraintLayout conTodoNewProc;
    private ConstraintLayout conTodoNewStep;
    private ConstraintLayout conTodoNewTodo;
    private ConstraintLayout conTodoNewTodoInfo;
    protected RecyclerView.LayoutManager mLayoutManager;
    private TodoNetRepository netRepository;
    private Gson gson;

    // conProc
    private Todo nowTodo;
    private Todo nextTodo;
    private String todoDesc;

    // conNewTodo
    private Proc nowProc;

    public static TodoFragment newInstance() {
        return new TodoFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        binding = FragmentTodoBinding.inflate(inflater, container, false);

        netRepository = new TodoNetRepository();
        gson = new Gson();

        conTodoMain = binding.todoConMain;
        conTodoProc = binding.todoConProc;
        conTodoNewProc = binding.todoConNewProc;
        conTodoNewStep = binding.todoConNewStep;
        conTodoNewTodo = binding.todoConNewTodo;
        conTodoNewTodoInfo = binding.todoConNewTodoInfo;

        todoConMainView();
//        todoConProcView();
//        todoConNewProcView();
//        todoConNewTodoView();

        return binding.getRoot();
    }

    private void hideAllCon() {
        conTodoMain.setVisibility(View.GONE);
        conTodoProc.setVisibility(View.GONE);
        conTodoNewProc.setVisibility(View.GONE);
        conTodoNewStep.setVisibility(View.GONE);
        conTodoNewTodo.setVisibility(View.GONE);
        conTodoNewTodoInfo.setVisibility(View.GONE);
    }

    private void todoConNewTodoInfoView() {
        hideAllCon();
        conTodoNewTodoInfo.setVisibility(View.VISIBLE);

        NewTodo thisNewTodo = new NewTodo();
        thisNewTodo.user_id = UserInfo.USERID;
        thisNewTodo.username = UserInfo.USERNAME;
        thisNewTodo.proc_id = nowProc.proc_id;

        binding.todoConNewTodoInfoProcTitle.setText(nowProc.proc_name);
        // todo_con_new_todo_info_text
        binding.todoConNewTodoInfoText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                thisNewTodo.todo_info = editable.toString();
                Log.v("todo_info", editable.toString());
            }
        });
        binding.todoConNewTodoInfoButtonOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                thisNewTodo.todo_option = "发起";

                Call<ResponseBody> call = null;
                try {
                    call = netRepository.postJsonStrFromJsonCall("todo/add", gson.toJson(thisNewTodo));
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

                call.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        String res = null;
                        try {
                            res = response.body().string();
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                        AddTodoResult result = gson.fromJson(res, AddTodoResult.class);

                        if (result.status_code == 0) {
                            todoConMainView();
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {

                    }
                });
            }
        });
        binding.todoConNewTodoInfoButtonCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                todoConMainView();
            }
        });

    }

    private void todoConNewTodoView() {

        hideAllCon();
        conTodoNewTodo.setVisibility(View.VISIBLE);

        Call<ResponseBody> call = netRepository.getCall("proc/getprocs");

        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String res = null;
                try {
                    res = response.body().string();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                Proc[] procList = gson.fromJson(res, Proc[].class);

//                List<Proc> procList = new ArrayList<>();
//                procList.add(new Proc(1, "请假", "请假流程"));
//                procList.add(new Proc(2, "车辆申请", "车辆申请流程"));

                RecyclerView recyclerView = binding.todoNewTodoProcListRecycler;
                recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
                recyclerView.setAdapter(new ProcListAdapter(Arrays.asList(procList)));
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });


        binding.todoNewTodoNewProcCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                todoConMainView();
            }
        });

        binding.todoNewTodoNewProcCreate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (nowProc != null)
                    todoConNewTodoInfoView();
            }
        });

//        todo_new_todo_new_proc_text
        binding.todoNewTodoNewProcText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                todoConNewProcView();
            }
        });
    }

    private void todoConNewProcView() {

        hideAllCon();
        conTodoNewProc.setVisibility(View.VISIBLE);


    }

    private void todoConProcView() {
        hideAllCon();
        conTodoProc.setVisibility(View.VISIBLE);

        TextView title = binding.todoProcStepName;
        TextView desc = binding.todoProcStepDesc;
        TextView username = binding.todoProcStepUsername;
        TextView create = binding.todoProcStepCreate;
        EditText todoInfo = binding.todoProcTodoInfo;
        Button cancel = binding.todoProcButtonCancel;
        Button ok = binding.todoProcButtonOk;

        title.setText(nowTodo.todo_name);
        desc.setText(nowTodo.todo_desc);
        username.setText(nowTodo.username);
        create.setText(nowTodo.todo_create.toString());
        todoInfo.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                nowTodo.todo_info = editable.toString();
            }
        });
        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                nowTodo.todo_option = "同意";
                nowTodo.todo_create = null;
                Call<ResponseBody> call = null;
                try {
                    call = netRepository.postJsonStrFromJsonCall("todo/done", gson.toJson(nowTodo));
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

                call.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
//                        Log.v("call", nowTodo);
                        todoConMainView();
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {

                    }
                });
            }
        });

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                nowTodo.todo_option = "拒绝";
                nowTodo.todo_create = null;
                TodoNetRepository netRepository = new TodoNetRepository();
                Call<ResponseBody> call = null;
                try {
                    call = netRepository.postJsonStrFromJsonCall("todo/done", (new Gson()).toJson(nowTodo));
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

                call.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        todoConMainView();
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {

                    }
                });
            }
        });
    }

    private void todoConMainView() {
        hideAllCon();
        conTodoMain.setVisibility(View.VISIBLE);

        RecyclerView recyclerViewNewTodo = binding.todoMainRecyclerNewTodo;
        RecyclerView recyclerViewMyTodo = binding.todoMainRecyclerMyTodo;
        RecyclerView recyclerViewDone = binding.todoMainRecyclerDone;

        TextView textViewNewTodo = binding.todoMainTextNewTodo;
        TextView textViewMyTodo = binding.todoMainTextMyTodo;
        TextView textViewDone = binding.todoMainTextDone;

        FloatingActionButton floatingActionButton = binding.fab;

        List<List<Todo>> list;
        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                todoConNewTodoView();
            }
        });

        TodoNetRepository netRepository = new TodoNetRepository();
        Call<ResponseBody> call = netRepository.getCall("todo/get?user_id=" + UserInfo.USERID);

        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String res = null;
                try {
                    res = response.body().string();
                    Log.v("RES", res);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                TodoListResult result = gson.fromJson(res, TodoListResult.class);
//                Log.v("TODO MAIN", list1.toString());

//                List<Todo> newList = new ArrayList<>();
//                newList.add(new Todo("请假", "张三"));
//                newList.add(new Todo("请假", "里斯"));
//                newList.add(new Todo("请假", "张是的"));
//                newList.add(new Todo("请假", "对方的"));
//                newList.add(new Todo("请假", "阿斯蒂芬"));
//                newList.add(new Todo("请假", "张三"));
//                newList.add(new Todo("请假", "里斯"));
//                newList.add(new Todo("请假", "张是的"));
//                newList.add(new Todo("请假", "对方的"));
//                newList.add(new Todo("请假", "阿斯蒂芬"));
//                newList.add(new Todo("请假", "张三"));
//                newList.get(0).todo_create = new Date();
//                newList.get(0).todo_id = 1;
//                newList.get(0).proc_id = 1;
//                newList.get(0).todo_desc = "qingjia";
//
//                List<List<Todo>> lists = new ArrayList<>();
//                lists.add(newList);
//                lists.add(newList);
//                lists.add(newList);
////                Gson gson  = new Gson();
//                String json_Str = gson.toJson(lists);
//                Log.v("Test json", json_Str);
//
//                List<Todo>[] listtest = gson.fromJson(json_Str, List[].class);
//                Log.v("Test json", listtest[0].toString());
//                Log.v("Test json", listtest[1].toString());
//                Log.v("Test json", listtest[2].toString());

                recyclerViewNewTodo.setLayoutManager(new LinearLayoutManager(getActivity()));
                TodoNewTodoAdapter adapterNewTodo = new TodoNewTodoAdapter(result.newTodoList);
                recyclerViewNewTodo.setAdapter(adapterNewTodo);

                recyclerViewMyTodo.setLayoutManager(new LinearLayoutManager(getActivity()));
                TodoNewTodoAdapter adapterMyTodo = new TodoNewTodoAdapter(result.myTodoList);
                recyclerViewMyTodo.setAdapter(adapterMyTodo);

                recyclerViewDone.setLayoutManager(new LinearLayoutManager(getActivity()));
                TodoNewTodoAdapter adapterDone = new TodoNewTodoAdapter(result.doneTodoList);
                recyclerViewDone.setAdapter(adapterDone);
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.v("ERROR", "ERROR");
            }
        });

        textViewNewTodo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                recyclerViewNewTodo.setVisibility(recyclerViewNewTodo.getVisibility()==View.VISIBLE ? View.GONE : View.VISIBLE);
                recyclerViewMyTodo.setVisibility(View.GONE);
                recyclerViewDone.setVisibility(View.GONE);
            }
        });
        textViewMyTodo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                recyclerViewNewTodo.setVisibility(View.GONE);
                recyclerViewMyTodo.setVisibility(recyclerViewMyTodo.getVisibility()==View.VISIBLE ? View.GONE : View.VISIBLE);
                recyclerViewDone.setVisibility(View.GONE);
            }
        });
        textViewDone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                recyclerViewNewTodo.setVisibility(View.GONE);
                recyclerViewMyTodo.setVisibility(View.GONE);
                recyclerViewDone.setVisibility(recyclerViewDone.getVisibility()==View.VISIBLE ? View.GONE : View.VISIBLE);
            }
        });
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    public class ProcListAdapter extends RecyclerView.Adapter<ProcListAdapter.ViewHolder> {
        private List<Proc> procList;

        public ProcListAdapter(List<Proc> procList) {
            this.procList = procList;
        }

        @NonNull
        @NotNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) {
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_todo_new_todo, parent, false);
            return new ProcListAdapter.ViewHolder(v);
        }

        @Override
        public void onBindViewHolder(@NonNull @NotNull ViewHolder holder, int position) {
            holder.getTextView().setText(procList.get(position).proc_name);
        }

        @Override
        public int getItemCount() {
            return procList.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            private TextView textView;
            public ViewHolder(View v) {
                super(v);
                v.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Log.v("ProListAda", getAdapterPosition() + " clicked");
                        nowProc = procList.get(getAdapterPosition());
//                        todoConNewTodoInfoView();
                    }
                });
                textView = (TextView) v.findViewById(R.id.item_todo_new_todo_proc_name);
            }

            public TextView getTextView() {
                return textView;
            }
        }
    }

    public class TodoNewTodoAdapter extends RecyclerView.Adapter<TodoNewTodoAdapter.ViewHolder> {

        private List<Todo> todoList;
        public class ViewHolder extends RecyclerView.ViewHolder {
            private final TextView textViewName;
            private final TextView textViewDesc;
            public ViewHolder(View view) {
                super(view);
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Log.v("TodoNewTodoAda", getAdapterPosition() + " clicked");
                        conTodoMain.setVisibility(View.GONE);
                        nowTodo = todoList.get(getAdapterPosition());
                        todoConProcView();
                    }
                });
                textViewName = (TextView) view.findViewById(R.id.item_todo_main_new_todo_name);
                textViewDesc = (TextView) view.findViewById(R.id.item_todo_main_new_todo_desc);
            }

            public TextView getTextViewName() {
                return textViewName;
            }

            public TextView getTextViewDesc() {
                return textViewDesc;
            }
        }

        public TodoNewTodoAdapter(List<Todo> todoList) {
            this.todoList = todoList;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_todo_main_new_todo, parent, false);
            return new TodoNewTodoAdapter.ViewHolder(v);
        }

        @Override
        public void onBindViewHolder(TodoNewTodoAdapter.ViewHolder holder, int position) {
            holder.getTextViewName().setText(todoList.get(position).username);
            holder.getTextViewDesc().setText(todoList.get(position).todo_name);
        }

        @Override
        public int getItemCount() {
            return todoList.size();
        }
    }
}